package cn.wolfcode.service.impl;

import cn.wolfcode.domain.TravelComment;
import cn.wolfcode.domain.UserInfo;
import cn.wolfcode.query.TravelCommentQuery;
import cn.wolfcode.repository.TravelCommentRepository;
import cn.wolfcode.service.ITravelCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository repository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private ITravelCommentService travelCommentService;
    @Override
    public void insert(TravelComment comment) {
        comment.setId(null);
        //维护关联的评论
        String refId = comment.getRefComment().getId();
        //如果不为空,改变添加的方式
        if (StringUtils.hasLength(refId)){
            //回复评论
            TravelComment travelComment = this.get(refId);
            comment.setRefComment(travelComment);
            comment.setType(TravelComment.TRAVLE_COMMENT_TYPE_COMMENT);
        }
        repository.save(comment);
    }

    @Override
    public void update(TravelComment comment) {
        repository.save(comment);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public TravelComment get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<TravelComment> listAll() {
        return repository.findAll();
    }

    @Override
    public Page query(TravelCommentQuery qo) {
        //创建查询对象
        Query query = new Query();
        //查询总条数
        long count = template.count(query, TravelComment.class);
        if (count == 0){
            return Page.empty();
        }
        Pageable page = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(page);
        List<TravelComment> list = template.find(query, TravelComment.class);
        PageImpl<TravelComment> travelComments = new PageImpl<>(list, page, count);
        return travelComments;
    }

    @Override
    public List<TravelComment> findByTravelId(String travelId) {
        List<TravelComment> list = repository.findByTravelId(travelId);
        return list;
    }

}
